package weaver.formmode.customjavacode.modeexpand.huangwm.SW003;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.customization.huangwm.utils.DBTools;
import com.customization.huangwm.utils.DateTools;
import com.customization.huangwm.utils.LogTool;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

/**
 * @Author Huangwm
 * @Date 2022-04-30
 * @Version 1.0
 * @description TODO 登记物料时如果为资产则插入到待登记资产列表
 */
public class RegisterAssetsToRecords extends AbstractModeExpandJavaCodeNew {
    private LogTool logTool = new LogTool("/log/SW003/huangwm/model/action/RegisterAssetsToRecords", false);
    private final String table = "uf_003_yyArrivalRecord";
    private String sql = "insert into " + table + "(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,MODEUUID" +
            ",eapItemCode,itemcode,assetName,assetDescribe,unit,quantity" +
            ",assetModel,manageDep,assetType,isAsset,thisSouce)" +
            "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    private DateTools dateTools = new DateTools();
    private DBTools dbTools = new DBTools();

    @Override
    public Map<String, String> doModeExpand(Map<String, Object> param) {
        Map<String, String> result = new HashMap<String, String>();
        BaseBean bean = new BaseBean();
        try {
            String uf_003_yyArrivalRecord_Modeid = bean.getPropValue("SW003", "uf_003_yyArrivalRecord_Modeid");
            User user = (User) param.get("user");
            int billid = -1;//数据id
            int modeid = -1;//模块id
            String importtype = param.getOrDefault("importtype", "0").toString();
            RequestInfo requestInfo = (RequestInfo) param.get("RequestInfo");
            if (requestInfo != null) {
                billid = Util.getIntValue(requestInfo.getRequestid());
                modeid = Util.getIntValue(requestInfo.getWorkflowid());
                logTool.writeLog("登记物料信息  userid=" + user.getUID() + "  billid=" + billid + " importtype=" + importtype);

                if (billid > 0 && modeid > 0) {
//					Property[] properties = requestInfo.getMainTableInfo().getProperty();
                    Map<String, String> mainDatas = new HashMap<>();
//					for (Property property : properties) {
//						//mainDatas.put(property.getName(), property.getValue());
//					}
                    String sql2 = "select * from uf_003_AssteInfo where id=" + billid;
                    RecordSet rs1 = new RecordSet();
                    rs1.execute(sql2);
                    rs1.next();
                    String[] columns = rs1.getColumnName();
                    for (int i = 0; i < columns.length; i++) {
                        mainDatas.put(columns[i].toLowerCase(), rs1.getString(columns[i]));
                    }
                    String yyType = dbTools.getEapTypeIdCompareYYID(rs1,mainDatas.get("assettype2"));
                    Float InventoryQuantity = Float.parseFloat(mainDatas.get("inventoryquantity"));
                    Float usedQuantity = Float.parseFloat(mainDatas.get("usedquantity"));
                    Float totalQuantity = Float.parseFloat(mainDatas.get("totalquantity"));

                    //判斷是否資產
                    String isAsset = mainDatas.get("isasset");
                    if (isAsset.equals("0")) {
                        String assetCode = mainDatas.get("assetcode");
                        String assetName = mainDatas.get("assetname");
                        String assetDescribe = mainDatas.get("assetdescribe");
                        String unit = mainDatas.get("unit");
                        String manageDep = mainDatas.get("managedep");
                        String assetModel = mainDatas.get("assetmodel");
                        //String assetType = mainDatas.get("assettype");

                        String modedatacreatedate = dateTools.getCurrentDate();
                        String modedatacreatetime = dateTools.getCurrentTime();
                        String uuid = dateTools.getUUID();
                        Object[] objects = new Object[]{
                                uf_003_yyArrivalRecord_Modeid, user.getUID(), 0, modedatacreatedate, modedatacreatetime, uuid,
                                billid, assetCode, assetName, assetDescribe, unit, (totalQuantity-usedQuantity), assetModel, manageDep, yyType, isAsset, 0
                        };
                        logTool.writeLog("插入数据：" + JSON.toJSONString(objects));
                        RecordSetTrans rs = new RecordSetTrans();
                        rs.setAutoCommit(false);
                        try {
                            rs.executeUpdate(sql, objects);
                        } catch (Exception e) {
                            rs.rollback();
                            e.printStackTrace();
                            logTool.writeLog("插入数据至待登记列表异常 \n" + e.getMessage());
                            result.put("errmsg", "插入数据至待登记列表异常 \n" + e.getMessage());
                            result.put("flag", "false");
                            return result;
                        }
                        rs.commit();
                        logTool.writeLog("开始进行权限重构=>>>" + dateTools.getCurrentTimes());
                        RecordSet rs2 = new RecordSet();
                        String sqlSearch = "select id from " + table + " where MODEUUID='" + uuid + "'";
                        rs2.execute(sqlSearch);
                        if (rs2.next()) {
                            logTool.writeLog("本次插入 " + table + " 表的数据id： " + rs2.getInt("id"));
                            refreshRight(user.getUID(), Integer.parseInt(uf_003_yyArrivalRecord_Modeid), rs2.getInt("id"));
                        }
                        logTool.writeLog("权限重构结束=>>>" + dateTools.getCurrentTimes());
                    }
                } else {
                    result.put("errmsg", "保存動作擴展接口执行失败 billid为空");
                    result.put("flag", "false");
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logTool.writeLog("保存動作擴展接口異常" + e.getMessage());
            result.put("errmsg", "保存動作擴展接口異常 msg=" + e.getMessage());
            result.put("flag", "false");
        }
        return result;
    }

    /**
     * 表单建模权限重构方法，重构后才能在台账里查看到数据
     *
     * @param creater    创建人
     * @param formmodeid 模块id
     * @param billid     数据id,即对应uf表里的id
     */
    public void refreshRight(int creater, int formmodeid, int billid) {
        try {
            ModeRightInfo modeRightInfo = new ModeRightInfo();
            //console.info("当前重构数据：creater=" + creater + "  formmodeid=" + formmodeid + "  billid=" + billid);
            modeRightInfo.setNewRight(true);
            modeRightInfo.editModeDataShare(creater, formmodeid, billid);
        } catch (Exception e) {
            logTool.writeLog("重构代码报错：creater=" + creater + "  formmodeid=" + formmodeid + "  billid=" + billid);
            logTool.writeLog(e.getMessage());
            e.printStackTrace();
        }
    }
}
